from flask import Blueprint, request, jsonify

from app.models.property import Property
from app.models.user import User
from app.routes.user import user_bp
from app.services.property_service import add_property_byUsername, update_property, get_property_byUsername, delete_property

property_bp = Blueprint("property", __name__)

#新增房源
@user_bp.route("/users/<int:id>/properties", methods=["POST"])
def add_property(id):
    data = request.json
    # 尝试根据路径中的 id 从数据库中获取 username
    user = User.query.get(id)
    if user is None:
        return jsonify({"code": 404, "msg": "用户不存在"}), 404
    username = user.username

    p_id=data.get("id")
    address = data.get("address")
    hoseType = data.get("hoseType")
    area = data.get("area")
    sumCost = data.get("sumCost")
    deposit = data.get("deposit")
    Decoration = data.get("Decoration")
    state = data.get("state")

    property = Property(
        id=p_id,  #时间戳作为房源编号
        username=username,
        address=address,
        hoseType=hoseType,
        area=area,
        sumCost=sumCost,
        deposit=deposit,
        Decoration=Decoration,
        state=state
    )

    try:
        add_property_byUsername(property, username)
        return jsonify({"code": 202, "msg": "房源添加成功"}), 202
    except:
        return jsonify({"code": 500, "msg": "房源添加失败"}), 500
#删除房源
@user_bp.route("/users/<int:id>/properties/<int:property_id>", methods=["DELETE"])
def delete_properties(id, property_id):
    user = User.query.get(id)
    if user is None:
        return jsonify({"code": 404, "msg": "用户不存在"}), 404
    username = user.username
    property = Property.query.get(property_id)
    if property is None:
        return jsonify({"code": 404, "msg": "房源不存在"}), 404
    if property.username != username:
        return jsonify({"code": 401, "msg": "房源的用户名不一致"}), 401

    try:
        delete_property(property_id)
        return jsonify({"code": 200, "msg": "房源删除成功"}), 200
    except Exception as e:
        print(f"删除房源时出错: {e}")
        return jsonify({"code": 500, "msg": "房源删除失败"}), 500

#编辑房源
@user_bp.route("/users/<int:id>/properties/<int:property_id>", methods=["PUT"])
def update_properties(id, property_id):
    data = request.json
    user = User.query.get(id)
    if user is None:
        return jsonify({"code": 404, "msg": "用户不存在"}), 404
    username = user.username
    property = Property.query.get(property_id)
    if property is None:
        return jsonify({"code": 404, "msg": "房源不存在"}), 404
    property.hoseType = data.get("hoseType")
    property.area = data.get("area")
    property.sumCost = data.get("sumCost")
    property.deposit = data.get("deposit")
    property.Decoration = data.get("Decoration")
    property.state = data.get("state")
    property.username = username
    property.address = data.get("address")

    try:
        update_property(property)
        return jsonify({"code": 202, "msg": "房源修改成功"}), 202
    except:
        return jsonify({"code": 500, "msg": "房源修改失败"}), 500

#查找房源
@user_bp.route("/users/<int:id>/properties", methods=["GET"])
def get_properties(id):
    user = User.query.get(id)
    if user is None:
        return jsonify({"code": 404, "msg": "用户不存在"}), 404

    try:
        properties = get_property_byUsername(user.username)
        print(properties)
        # 将查询结果转换为可 JSON 序列化的列表
        property_list = []
        for prop in properties:
            property_data = {
                "id": prop.id,
                "username": prop.username,
                "address": prop.address,
                "hoseType": prop.hoseType,
                "area": prop.area,
                "sumCost": prop.sumCost,
                "deposit": prop.deposit,
                "Decoration": prop.Decoration,
                "state": prop.state
            }
            property_list.append(property_data)
        print(property_list)
        return jsonify({"code": 200, "msg": "房源查找成功", "data": property_list}), 200
    except Exception as e:
        print(f"查找房源时出错: {e}")
        return jsonify({"code": 500, "msg": "房源查找失败"}), 500

#查找房源（根据类型判断）
@user_bp.route("/properties", methods=["GET"])
def get_properties_by_searchType():

    searchType = request.args.get('searchType')
    searchQuery = request.args.get('searchQuery')
    print(searchType)
    print(searchQuery)
    if not searchType:
        return jsonify({"code": 400, "msg": "缺少必要的参数 searchType"}), 400

    try:
        if (searchType == "address" ):
            # 查找 address 为 searchType 的房源信息
            print(searchQuery)
            properties_by_address = Property.query.filter(Property.address.ilike(f"{searchQuery}%")).all()

            if properties_by_address:
                property_list = []
                for prop in properties_by_address:
                    property_data = {
                        "id": prop.id,
                        "username": prop.username,
                        "address": prop.address,
                        "hoseType": prop.hoseType,
                        "area": prop.area,
                        "sumCost": prop.sumCost,
                        "deposit": prop.deposit,
                        "Decoration": prop.Decoration,
                        "state": prop.state
                    }
                    property_list.append(property_data)
                return jsonify({"code": 200, "msg": "根据 address 查找房源成功", "data": property_list}), 200
            else:
                # 则返回空列表
                return jsonify({"code": 200, "msg": "根据 address 查找房源成功", "data": []}), 200

        else:
            # 若 address 未找到匹配，查找 hoseType 为 searchType 的房源信息
            properties_by_hosetype = Property.query.filter(Property.hoseType.ilike(f"{searchQuery}%")).all()
            if properties_by_hosetype:
                property_list = []
                for prop in properties_by_hosetype:
                    property_data = {
                        "id": prop.id,
                        "username": prop.username,
                        "address": prop.address,
                        "hoseType": prop.hoseType,
                        "area": prop.area,
                        "sumCost": prop.sumCost,
                        "deposit": prop.deposit,
                        "Decoration": prop.Decoration,
                        "state": prop.state
                    }
                    property_list.append(property_data)
                return jsonify({"code": 200, "msg": "根据 hoseType 查找房源成功", "data": property_list}), 200
            else:
                # 则返回空列表
                return jsonify({"code": 200, "msg": "根据 hoseType 查找房源成功", "data": []}), 200
            # 若都未找到匹配结果


    except Exception as e:
        print(f"查找房源时出错: {e}")
        return jsonify({"code": 500, "msg": "房源查找失败"}), 500